<?php

namespace app\model;

use think\Model;
use think\model\relation\HasOne;

class SupplierPriceRule extends Model
{
    public function supplierInfo(): HasOne
    {
        return $this->hasOne(Supplier::class, "id", "supplier");
    }

    public function saveData(): array
    {
        $data = request()->post();
//        dd($data);
        if ($data['rule_dates'] == 1) {
            $data['start_time'] = $data['timer'] . " 00:00:00";
            $data['end_time'] = "2099-12-31 23:59:59";
        } else {
            $data['start_time'] = $data['timer'][0] . " 00:00:00";
            $data['end_time'] = $data['timer'][1] . " 23:59:59";
        }
        unset($data['timer']);
        $data['state'] = strtotime($data['start_time']) > time() ? 0 : (strtotime($data['end_time']) < time() ? 2 : 1);
        if (!empty($data['id'])) {
            //编辑策略
            //获取当前策略是否生效
//            $count = $this->where('id', $data['id'])->where('start_time', '<', date("Y-m-d H:i:s"))->where('end_time', '>', date("Y-m-d H:i:s"))->where('state', 1)->count();
//            if ($count > 0) {
//                throw new \Exception('当前策略生效中,不能编辑');
//            }
            $this->exists()->save($data);
            return $this->toArray();
        }
        //添加策略
        $supplier = $data['supplier'];
        unset($data['supplier']);
        $that = $this;
        $items = array_map(function ($item) use ($data, $that) {
//            $count = $that->where('supplier', $item)->where('start_time', '<', date("Y-m-d H:i:s"))->where('end_time', '>', date("Y-m-d H:i:s"))->where('state', 1)->count();
            return array_merge(['supplier' => $item], $data);
        }, $supplier);
        $items = array_filter($items);
        $this->saveAll(array_values($items));
        return $this->toArray();
    }

    public function pageData(): array
    {
        $param = request()->param();
        $data = $this->with(['supplierInfo'])->when(!empty($param['name']),function ($query) use ($param){
            $query->whereLike('name', "%{$param['name']}%");
        })->when(isset($param['supplier']) && $param['supplier'] != '',function ($query) use ($param){
            $supplier = (string)$param['supplier'];
            if(strlen($supplier)){
                $query->where('supplier',$supplier);
            }
        })->when(isset($param['state']) && $param['state'] != '',function ($query) use ($param){
            $state = (string)$param['state'];
            if(strlen($state)){
                $query->where('state',$state);
            }
        })->when(isset($param['rule']) && $param['rule'] != '',function ($query) use ($param){
            $rule = (string)$param['rule'];
            if(strlen($rule)){
                $query->where('rule',$rule);
            }
        })->order(['supplier'=>'asc','start_time' => 'desc', 'create_time' => 'desc'])->paginate(['list_rows' => 30, 'page' => $param['page'] ?? 1])->toArray();
        $configPrice = file_get_contents("./station_config/price.conf");
        $configPrice = json_decode($configPrice, true);
        $data['data'] = array_map(function ($its) use ($configPrice) {
            $its['prices'] = ($its['rule'] == 1 ? (float)$its['number'] : (((float)$its['number']) . "%"));
            if ($its['prices'] != 0) {
                $its['prices'] = ($its['price_unit'] == 1 ? '+' : '-') . $its['prices'];
            }
            $its['init_price'] = matchDiscount($configPrice,$its);
            return $its;
        }, $data['data']);
        return pageData($data);
    }

    public function detailData(): array
    {
        $id = request()->param('id');
        $data = $this->find($id);
        if (empty($data)) throw new \Exception('数据不存在');
        $data = $data->toArray();
        $data['number'] = (float)$data['number'];
        $data['timer'] = match ($data['rule_dates']) {
            1 => date("Y-m-d", strtotime($data['start_time'])),
            default => [date("Y-m-d", strtotime($data['start_time'])), date("Y-m-d", strtotime($data['end_time']))]
        };
        return $data;
    }
}
